package org.example.innovate.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import org.example.innovate.domain.Recipe;
import org.example.innovate.domain.User;
import org.example.innovate.dto.PageDTO;
import jakarta.annotation.Resource;
import org.codehaus.jettison.json.JSONException;
import org.example.innovate.common.CommonResponse;
import org.example.innovate.domain.Dish;
import org.example.innovate.service.DishService;
import org.example.innovate.vo.*;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartRequest;

import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/dish")
@Valid
public class DishController {
    @Resource
    DishService dishService;
    @GetMapping("/update")
    public CommonResponse<String> update() throws org.codehaus.jettison.json.JSONException {
        return dishService.updateData();
    }
    @GetMapping("/update0")
    public CommonResponse<User> update0() throws org.codehaus.jettison.json.JSONException, IOException {
        return dishService.updateUser();
    }
    @PostMapping("/Hotdish")
    public CommonResponse<DishVo> getHotDish(@RequestBody String json) throws JSONException {
        JSONObject jsonObject = JSON.parseObject(json);
        PageDTO pageDTO=jsonObject.toJavaObject(PageDTO.class);
        return dishService.getHotDish(pageDTO);
    }
    @PostMapping("/PersonDish")
    public CommonResponse<DishVo> getPersonDish(@RequestBody String json,HttpServletRequest request) throws JSONException {
        JSONObject jsonObject = JSON.parseObject(json);
        PageDTO pageDTO=jsonObject.toJavaObject(PageDTO.class);
        return dishService.getPersonDish(pageDTO,request);
    }
    @PostMapping("/category")
    public CommonResponse<List<DishOneVo>> getCategory(@RequestBody String category){
        JSONObject jsonObject=JSON.parseObject(category);
        category=jsonObject.getString("category");
        System.out.println(category);
        return dishService.getCategory(category);
    }
    //@PostMapping("/addDish")
    //public CommonResponse<DishBodyVo> addDish(@RequestBody Dish dish, @RequestBody List<Recipe> recipes,@RequestBody List<String> body,@RequestBody List<String> material){
    //    return dishService.addDish(dish,recipes,body,material);
    //}
    @PostMapping("/dishBody")
    public CommonResponse<DishBodyVo> getDishBody(@RequestBody Dish dish,HttpServletRequest request) throws IOException {
        return dishService.getdishBody(dish,request);
    }
    @PostMapping("/search")
    public CommonResponse<List<DishOneVo>> search(@RequestBody String content,HttpServletRequest request) throws IOException {
        JSONObject jsonObject = JSON.parseObject(content);
        content=jsonObject.getString("content");
        return dishService.search(content,request);
    }

//    @RequestMapping(value = "/upload", headers = "content-type=multipart/form-data")
//    @ResponseBody
//    public CommonResponse<uploadVo> upload(MultipartHttpServletRequest request, @RequestBody uploadVo up) throws IOException {
//        MultipartFile cover_image = request.getFile("cover_image");
//        if (cover_image != null) {
//            System.out.println(cover_image.getOriginalFilename());
//        }
//        return null ;
//    }


// 如下代码只保留了主逻辑
@RequestMapping(value = "/upload", headers = "content-type=multipart/form-data")
@ResponseBody
public CommonResponse<uploadVo> uploadFile(MultipartHttpServletRequest request, uploadVo up) throws IOException{
    System.out.println(request);
    List<MultipartFile> cover_image = new ArrayList<>();
    if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        // 打印所有普通参数
        Map<String, String[]> parameterMap = multipartRequest.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            System.out.println("Parameter '" + entry.getKey() + "': ");
            for (String value : entry.getValue()) {
                System.out.println("  Value: " + value);
            }
        }

        // 打印所有上传的文件
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
            MultipartFile file = entry.getValue();
            System.out.println("File Parameter '" + entry.getKey() + "': ");
            System.out.println("  OriginalFileName: " + file.getOriginalFilename());
            System.out.println("  Size: " + file.getSize());
            System.out.println("  ContentType: " + file.getContentType());
            cover_image.add(file);
        }

        // 或者使用迭代器遍历所有部分（multipart elements）
//        Iterator<String> iterator = multipartRequest.getFileNames();
//        while (iterator.hasNext()) {
//            String elementName = iterator.next();
//            MultipartFile multipartFile = multipartRequest.getFile(elementName);
//            System.out.println("Iterated File Parameter '" + elementName + "': ");
//            System.out.println("  OriginalFileName: " + multipartFile.getOriginalFilename());
//            System.out.println("  Size: " + multipartFile.getSize());
//            System.out.println("  ContentType: " + multipartFile.getContentType());
//        }
    } else {
        System.out.println("This is not a multipart request.");
    }
    System.out.println((long) cover_image.size());
    String token=request.getHeader("token");
    return dishService.upload(cover_image,up,token);
}

    @PostMapping("/{userId}")
    public CommonResponse<DishVo> getDishByUserId(@PathVariable("userId") Integer userId,@RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        PageDTO pageDTO=jsonObject.toJavaObject(PageDTO.class);
        return dishService.getDishByUserId(userId,pageDTO);
    }

    @PostMapping("/back")
    public CommonResponse<BackVo> setBack(@RequestBody BackVo backVo,HttpServletRequest request) throws IOException {
        return dishService.setBack(backVo,request);
    }

    @GetMapping("/repair")
    public CommonResponse<Integer> repair()
    {
        return dishService.repair();
    }
}